package adrian.sunlight.ws.axis2;

import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;

public class ResourceLockingService {
	
	private Vector<String> LockedResources = new Vector<String>();
	private Vector<Timer>  Timers		   = new Vector<Timer>();
	private String 		   error		   = new String();
	
	public void updateResourceTimer(final String rname, int seconds){
		int index = LockedResources.indexOf(rname);
		
		if(index >= 0){
			Timer t = Timers.get(index);
			
			t.cancel();
			
			TimerTask task	= new TimerTask(){
				public void run(){
					unlockResource(rname);
				}
			};
				
			t.schedule(task, seconds * 1000);
		}
	}
	
	public void lockResource(final String rname, int seconds){
		int index = LockedResources.indexOf(rname);
		
		if(index >= 0){
			;
		}
		else{//nu se poate bloca o resursa de doua ori;
			LockedResources.add(rname);
			
			TimerTask task	= new TimerTask(){
				public void run(){
					try{
						unlockResource(rname);
					}
					catch(Exception e){
						error =  e.toString();
					}
				}
			};
			
			Timer t = new Timer();
			t.schedule(task, seconds * 1000);
			
			Timers.add(t);
		}
	}
	
	public void unlockResource(String rname){
		
		int index = LockedResources.indexOf(rname);
		
		if(index >= 0){
			//------~ Anuleaza timer-ul ~------//
			Timer t = Timers.get(index);
				  t.cancel();
				  t.purge();
			
			//------~ Sterge resursa blocata ~------//
			LockedResources.remove(rname);
		}
	}
	
	public boolean isResourceLocked(final String rname){
		int index = LockedResources.indexOf(rname);
		
		if(index >= 0){
			return true;
		}
		
		return false;
	}
	
	public void unlockAllResources(){
		while(this.LockedResources.size() > 0){
			int i = this.LockedResources.size() -1;
			
			this.LockedResources.remove(i);
			Timer t = Timers.get(i);
			  	  t.cancel();
			  	  t.purge();
		}
	}
	
	public String getError(){
		return error;
	}

}
